<!--
/**
 * Created by PhpStorm.
 * User: Devmc
 * Date: 2021/4/24
 * Time: 22:05
 */
-->
<template>
  <div>
    <comment-container
        v-for="(item, index) in tableData"
        :key="`${item.commentId}-${item.userId}-${index}`"
        :user-object-data="userObjectData"
        :data="item.comment.comment"
        :commentId="item.commentId"
        @change="getComment()">

      <slot>
        <comment-container
            v-for="(reply, replyIndex) in item.comment.reply"
            :key="`${item.commentId}-${item.userId}-${replyIndex}`"
            :user-object-data="userObjectData"
            :data="reply"
            :reply="true"
            :commentId="item.commentId"
            :reply-index="replyIndex"
            @change="getComment()">
        </comment-container>
      </slot>
    </comment-container>
  </div>
</template>

<script>
import CommentContainer from "./CommentContainer";
import modelUser from "../models/user";

export default {
  name: "CommentList",
  components: {CommentContainer},
  props: {
    // 是否只获取一条
    commentId: {
      type: Number,
      default: -1
    },
  },
  data() {
    return {
      // 数据
      tableData: [
        /*{
          "comment": "string",
          "commentId": 0,
          "userId": 0
        }*/
      ],
      userObjectData: {},
    }
  },
  created() {
    // 获取留言
    this.getComment();

    // 先设置无数据
    this.$emit('update:hasData', false);
  },
  mounted() {
  },
  methods: {
    /**
     * 获取评论
     */
    getComment() {
      // 告诉外部我变了
      this.$emit('change');

      const url = this.$store.state.api + '/comment/list?pageNum=1&pageSize=500';
      const body = this.commentId == -1 ? {userId: this.$store.state.userData.userId} : {commentId: this.commentId}

      this.axios.post(url, body).then((response) => {
        if (response.data.code == 200) {
          let tableData = response.data.data.records;
          if (tableData.length) {
            modelUser.getUserObjectData().then(userObjectData => {
              this.userObjectData = userObjectData;
              this.tableData = tableData.map((item) => {
                item.comment = JSON.parse(item.comment);
                return item;
              });
              // 告诉父组件有数据
              this.$emit('update:hasData', true);
            });
          }
        }
      }).catch((error) => {
        console.log(error);
      });
    }
  },
  watch: {
    // ID变的时候改变数据
    commentId() {
      this.getComment();
    }
  }
}
</script>

<style lang="scss">

</style>